package servletsWithoutStruts;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.IDAOPhoneNumber;

/**
 * Servlet implementation class ModifyPhoneServlet
 */
public class ModifyPhoneServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModifyPhoneServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phoneId = request.getParameter("phoneId");
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IDAOPhoneNumber daoPhone = (IDAOPhoneNumber) context.getBean("daophonenumber");		
		request.setAttribute("contactId", request.getParameter("contactId"));
		if (phoneId != null) {
			request.setAttribute("phone", daoPhone.getPhoneNumber(Long.valueOf(phoneId)));
		}
		request.getRequestDispatcher("modifyPhoneNumber.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phoneId = request.getParameter("phoneId");
		String contactId = request.getParameter("contactId");
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IDAOPhoneNumber daoPhone = (IDAOPhoneNumber) context.getBean("daophonenumber");
		if(phoneId.equals("") ){
			daoPhone.addPhoneToContact( Long.valueOf(contactId), request.getParameter("phoneKind"), request.getParameter("phoneNumber"));
			request.setAttribute("id", contactId);response.sendRedirect(response.encodeRedirectURL("ModifyContactServlet?id=" + contactId));
		} else {
			daoPhone.modifyPhoneNumber(Long.valueOf(phoneId) ,  request.getParameter("phoneKind"), request.getParameter("phoneNumber"));
			request.setAttribute("id", contactId);
			response.sendRedirect(response.encodeRedirectURL("ModifyContactServlet?id=" + contactId));
		}
	}

}
